package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.SupplyListStatus;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.PoSyupplyDto;
import com.yunyao.common.dto.excel.SupplyExcelDto;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.*;
import com.yunyao.framework.dto.posyupply.PoSosyupplySaveDto;
import com.yunyao.framework.dto.posyupply.PoSosyupplyUploadedDto;
import com.yunyao.framework.service.PoSyupplyService;
import com.yunyao.framework.vo.posupply.PoSyupplyVo;
import com.yunyao.framework.vo.posupply.PoSyupplyinfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PoSyupplyServiceImpl implements PoSyupplyService {
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;
    @Autowired
    private IBamuSoSupplyService iBamuSoSupplyService;
    @Autowired
    private IBamuPoSupplyService iBamupoSupplyService;
    @Autowired
    private IBamuSupplyApplyService iBamuSupplyApplyService;

    @Autowired
    private IBamuAuditConfirmHistoryService auditConfirmHistoryService;

    @Autowired
    private  IBamuSpReconciliationOrderService iBamuSpReconciliationOrderService;

    @Override
    public YResult<PageResult<PoSyupplyVo>> pageList(PoSyupplyDto poSyupplyDto) {
//        构建查询条件
        LambdaQueryWrapper<BamuPoSupply> queryWrapper = new LambdaQueryWrapper<BamuPoSupply>()
                .eq(StringUtils.isNotEmpty(BaseContext.getUserInfo().getTenantId()),BamuPoSupply::getTenantId, BaseContext.getUserInfo().getTenantId())
                .eq(StringUtils.isNotEmpty(poSyupplyDto.getApplyId()),BamuPoSupply::getApplyId, poSyupplyDto.getApplyId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getProjectId()),BamuPoSupply::getProjectId, poSyupplyDto.getProjectId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getContractId()),BamuPoSupply::getContractId, poSyupplyDto.getContractId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getSaleContractId()),BamuPoSupply::getContractId, poSyupplyDto.getSaleContractId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getContractMethod()),BamuPoSupply::getContractMethod, poSyupplyDto.getContractMethod())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getReconciliationStatus()),BamuPoSupply::getReconciliationStatus, poSyupplyDto.getReconciliationStatus())
                .eq(poSyupplyDto.getSupplyStatus() != null,BamuPoSupply::getSupplyStatus, poSyupplyDto.getSupplyStatus())
                .eq(BamuPoSupply::getIsDeleted, DataDeletedStatus.NO.getType())
                .like(StringUtils.isNotBlank(poSyupplyDto.getContractName()),BamuPoSupply::getContractName, poSyupplyDto.getContractName())
                .like(StringUtils.isNotBlank(poSyupplyDto.getOrderSn()),BamuPoSupply::getOrderSn, poSyupplyDto.getOrderSn())
                .like(StringUtils.isNotBlank(poSyupplyDto.getOrderName()),BamuPoSupply::getOrderName, poSyupplyDto.getOrderName())
                .like(StringUtils.isNotBlank(poSyupplyDto.getProjectName()),BamuPoSupply::getProjectName, poSyupplyDto.getProjectName())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()),BamuPoSupply::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),BamuPoSupply::getSupplierId, BaseContext.getSupplierList())
                .notIn(CollectionUtils.isNotEmpty(poSyupplyDto.getIdList()), BamuPoSupply::getId,poSyupplyDto.getIdList())
                .orderByDesc(BamuPoSupply::getCreatedAt);

        //已经新增的单据不在显示
        LambdaQueryWrapper<BamuSpReconciliationOrder> wrapper = new LambdaQueryWrapper<>();
        List<BamuSpReconciliationOrder> bamuSpReconciliationOrders = iBamuSpReconciliationOrderService.list(wrapper);
        List<String> ids = new ArrayList<>();
        for (BamuSpReconciliationOrder order:bamuSpReconciliationOrders){
            ids.add(order.getSupplyId());
        }
        if(CollectionUtils.isNotEmpty(ids)){
            queryWrapper.notIn(BamuPoSupply::getId,ids);
        }
        // 分页查询
        IPage<BamuPoSupply> poSupplyPage = new Page<>(poSyupplyDto.getPageIndex(), poSyupplyDto.getPageSize());
        poSupplyPage = iBamupoSupplyService.page(poSupplyPage,queryWrapper);
        // 处理查询结果
        if(CollectionUtils.isEmpty(poSupplyPage.getRecords())){
            return YResult.success(new PageResult<>());
        }
        // 转换为VO对象列表
        List<PoSyupplyVo> poSyupplyVoList = daoToVoList(poSupplyPage.getRecords());
        // 返回分页结果
        return YResult.success(new PageResult<>(poSyupplyVoList,poSupplyPage.getCurrent(),poSupplyPage.getSize(),poSupplyPage.getPages(),poSupplyPage.getTotal()));
    }
    private List<PoSyupplyVo> daoToVoList(List<BamuPoSupply> records) {

        return records.stream().map(this::daoToVo).collect(Collectors.toList());
    }

    private PoSyupplyVo daoToVo(BamuPoSupply bamuPoSupply) {
        PoSyupplyVo poSyupplyVo = new PoSyupplyVo();
        BeanUtils.copyProperties(bamuPoSupply, poSyupplyVo);
        return poSyupplyVo;
    }


    @Override
    public YResult<PoSyupplyinfoVO> getPoSupplyById(String id) {
        BamuPoSupply bamuPoSupply = iBamupoSupplyService.getById(id);
        // 处理查询结果
        if (Objects.isNull(bamuPoSupply)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        BamuSupplyApply bamuSupplyApply = iBamuSupplyApplyService.getById(bamuPoSupply.getApplyId());
        PoSyupplyinfoVO poSupplinfoVO = daoToInfoVO(bamuPoSupply);
        poSupplinfoVO.setCopperPrice(bamuSupplyApply.getCopperPrice());
        poSupplinfoVO.setCopperDate(bamuSupplyApply.getCopperDate());
        poSupplinfoVO.setCopperUpdatePersonName(bamuSupplyApply.getCopperUpdatePersonName());
        poSupplinfoVO.setCopperUpdatePersonId(bamuSupplyApply.getCopperUpdatePersonId());
        List<BamuAuditConfirmHistory> confirmHistory = iBamuAuditConfirmHistoryService.getListByBizIdAndType(bamuSupplyApply.getId(),null, false);
        if (CollectionUtils.isNotEmpty(confirmHistory)) {
            poSupplinfoVO.setSupplierFiles(confirmHistory.get(0).getFile());
        }
        return YResult.success(poSupplinfoVO);
    }

    private PoSyupplyinfoVO daoToInfoVO(BamuPoSupply bamuPoSupply) {
        PoSyupplyinfoVO poSyupplyinfoVO = new PoSyupplyinfoVO();
        BeanUtils.copyProperties(bamuPoSupply, poSyupplyinfoVO);
        poSyupplyinfoVO.setSupplyFile(bamuPoSupply.getSupplyFile());
        poSyupplyinfoVO.setSupplyUserId(bamuPoSupply.getSupplyUserId());
        poSyupplyinfoVO.setSupplyUserName(bamuPoSupply.getSupplyUserName());
        poSyupplyinfoVO.setSupplyConfirmFile(bamuPoSupply.getSupplyConfirmFile());
        return poSyupplyinfoVO;
    }




    @Override
    public YResult<String> saveInfo(PoSosyupplySaveDto saveDto) {
        BamuPoSupply bamuPoSupply = new BamuPoSupply();
        BeanUtils.copyProperties(saveDto,bamuPoSupply);
        bamuPoSupply.setCreatedAt(saveDto.getCreatedAt());
        bamuPoSupply.setShipmentAt(saveDto.getShipmentAt());
        iBamupoSupplyService.saveOrUpdate(bamuPoSupply);
        return YResult.success(bamuPoSupply.getId());
    }

    @Override
    public YResult<String> uploade(PoSosyupplyUploadedDto saveDto) {
        BamuPoSupply bamuPoSupply = iBamupoSupplyService.getById(saveDto.getId());
        /**
         * 云采发货单
         */
        bamuPoSupply.setSupplyConfirmFile(saveDto.getSupplyConfirmFile());
        bamuPoSupply.setId(saveDto.getId());
        /**
         * 厂家发货单
         */
        bamuPoSupply.setSupplyFile(saveDto.getShipmentFiles());
        bamuPoSupply.setShipmentFiles(saveDto.getShipmentFiles());
        bamuPoSupply.setSupplyUserId(BaseContext.getUserId());
        bamuPoSupply.setSupplyUserName(BaseContext.getUserInfo().getRealName());
        /**
         * 供货上传后 状态改为待云采确认
         */
        bamuPoSupply.setSupplyStatus(SupplyListStatus.WAIT_YUNCAI_CONFIRMATION.getType());
        iBamupoSupplyService.saveOrUpdate(bamuPoSupply);

        BamuAuditConfirmHistory bamuAuditConfirmHistory = new BamuAuditConfirmHistory();
        bamuAuditConfirmHistory.setBizId(saveDto.getId());
        bamuAuditConfirmHistory.setMark(saveDto.getMark());
        bamuAuditConfirmHistory.setFile(saveDto.getShipmentFiles());
        bamuAuditConfirmHistory.setType("0");
        iBamuAuditConfirmHistoryService.saveOrUpdate(bamuAuditConfirmHistory);

        /**
         *
         */
        String shipmentFiles = bamuPoSupply.getShipmentFiles();
        LambdaQueryWrapper<BamuSoSupply> queryWrapper = new LambdaQueryWrapper<BamuSoSupply>();
        queryWrapper.eq(BamuSoSupply::getPoSupplyId,saveDto.getId()).eq(BamuSoSupply::getIsDeleted,DataDeletedStatus.NO.getType());
        List<BamuSoSupply> soSupplyList = iBamuSoSupplyService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(soSupplyList)){
            soSupplyList.forEach(item->{
                item.setSupplyStatus(SupplyListStatus.WAIT_YUNCAI_CONFIRMATION.getType());
                item.setSupplyFile(shipmentFiles);
                item.setShipmentFiles(shipmentFiles);
            });
            iBamuSoSupplyService.saveOrUpdateBatch(soSupplyList);
        }
        return YResult.success(bamuPoSupply.getId());
    }

    @Override
    public YResult<Boolean> deleteInfo(PoSosyupplySaveDto saveDto) {
        // 根据ID查询要删除的BamuPoSupply对象
        BamuPoSupply bamuPoSupply = iBamupoSupplyService.getById(saveDto.getId());

        // 如果对象不存在，返回错误信息
        if (bamuPoSupply == null) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 调用Service层删除方法
        boolean removed = iBamupoSupplyService.removeById(saveDto.getId());

        // 返回删除结果
        if (removed) {
            return YResult.success(true);
        } else {
            return YResult.error(ResultMsgEnum.ERROR);
        }
    }

    @Override
    public List<PoSyupplyinfoVO> getSupplyByapplyId(String id) {
        // 根据项目订单id查询供货订单
        LambdaQueryWrapper<BamuSupplyApply> supplyApplyLambdaQueryWrapper= new LambdaQueryWrapper<BamuSupplyApply>()
                .eq(BamuSupplyApply::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuSupplyApply::getApplyId, id);

        BamuSupplyApply bamuSupplyApply = iBamuSupplyApplyService.getOne(supplyApplyLambdaQueryWrapper);
        if(bamuSupplyApply == null){
            return null;
        }
        LambdaQueryWrapper<BamuPoSupply> wrapper = new LambdaQueryWrapper<BamuPoSupply>()
                .eq(BamuPoSupply::getApplyId,bamuSupplyApply.getId()).eq(BamuPoSupply::getIsDeleted, DataDeletedStatus.NO.getType());
        List<BamuPoSupply> bamuSoSupplyList = iBamupoSupplyService.list(wrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(bamuSoSupplyList)) {
            return Collections.emptyList(); // 返回空列表而不是进行类型转换
        }
        return bamuSoSupplyList.stream().map(this::daoToInfoVO1).collect(Collectors.toList());
    }

    private PoSyupplyinfoVO daoToInfoVO1(BamuPoSupply bamuSoSupply) {
        PoSyupplyinfoVO soSupplinfoVO = new PoSyupplyinfoVO();
        BeanUtils.copyProperties(bamuSoSupply, soSupplinfoVO);
        return soSupplinfoVO;
    }


    /**
     *
     * @param orderDto
     * @return
     */
    @Override
    public YResult<String>  audit(PoSyupplyDto orderDto) {
        /**
         * 云采确认
         */
        BamuPoSupply poSupply = iBamupoSupplyService.getById(orderDto.getId());
        poSupply.setSupplyFile(orderDto.getAuditFileUrl());
        poSupply.setSupplyStatus(SupplyListStatus.WAIT_PROJECT_ACCEPTANCE.getType());
        iBamupoSupplyService.saveOrUpdate(poSupply);
        LambdaQueryWrapper<BamuSoSupply> queryWrapper = new LambdaQueryWrapper<BamuSoSupply>();
        queryWrapper.eq(BamuSoSupply::getPoSupplyId,poSupply.getId());
        List<BamuSoSupply> supplyList = iBamuSoSupplyService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(supplyList)){
            for (BamuSoSupply supply : supplyList) {
                supply.setStatus(SupplyListStatus.WAIT_PROJECT_ACCEPTANCE.getType());
                supply.setSupplyFile(orderDto.getAuditFileUrl());
            }
            iBamuSoSupplyService.saveOrUpdateBatch(supplyList);
        }
        auditConfirmHistoryService.insertRecord(orderDto.getId(), new Date(), null, orderDto.getAuditFileUrl(), orderDto.getAuditReason(), ConvertUtil.getIntValue(orderDto.getAuditStatus()), "1", BaseContext.getUserInfo().getRealName());
        return YResult.success("审核成功");
    }


    @Override
    public List<SupplyExcelDto> export(PoSyupplyDto poSyupplyDto) {
        LambdaQueryWrapper<BamuPoSupply> queryWrapper = new LambdaQueryWrapper<BamuPoSupply>()
                .eq(StringUtils.isNotEmpty(BaseContext.getUserInfo().getTenantId()),BamuPoSupply::getTenantId, BaseContext.getUserInfo().getTenantId())
                .eq(StringUtils.isNotEmpty(poSyupplyDto.getApplyId()),BamuPoSupply::getApplyId, poSyupplyDto.getApplyId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getProjectId()),BamuPoSupply::getProjectId, poSyupplyDto.getProjectId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getContractId()),BamuPoSupply::getContractId, poSyupplyDto.getContractId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getSaleContractId()),BamuPoSupply::getContractId, poSyupplyDto.getSaleContractId())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getContractMethod()),BamuPoSupply::getContractMethod, poSyupplyDto.getContractMethod())
                .eq(StringUtils.isNotBlank(poSyupplyDto.getReconciliationStatus()),BamuPoSupply::getReconciliationStatus, poSyupplyDto.getReconciliationStatus())
                .eq(poSyupplyDto.getSupplyStatus() != null,BamuPoSupply::getSupplyStatus, poSyupplyDto.getSupplyStatus())
                .eq(BamuPoSupply::getIsDeleted, DataDeletedStatus.NO.getType())
                .like(StringUtils.isNotBlank(poSyupplyDto.getContractName()),BamuPoSupply::getContractName, poSyupplyDto.getContractName())
                .like(StringUtils.isNotBlank(poSyupplyDto.getOrderSn()),BamuPoSupply::getOrderSn, poSyupplyDto.getOrderSn())
                .like(StringUtils.isNotBlank(poSyupplyDto.getOrderName()),BamuPoSupply::getOrderName, poSyupplyDto.getOrderName())
                .like(StringUtils.isNotBlank(poSyupplyDto.getProjectName()),BamuPoSupply::getProjectName, poSyupplyDto.getProjectName())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()),BamuPoSupply::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),BamuPoSupply::getSupplierId, BaseContext.getSupplierList())
                .notIn(CollectionUtils.isNotEmpty(poSyupplyDto.getIdList()), BamuPoSupply::getId,poSyupplyDto.getIdList())
                .orderByDesc(BamuPoSupply::getCreatedAt);

        //已经新增的单据不在显示
        LambdaQueryWrapper<BamuSpReconciliationOrder> wrapper = new LambdaQueryWrapper<>();
        List<BamuSpReconciliationOrder> bamuSpReconciliationOrders = iBamuSpReconciliationOrderService.list(wrapper);
        List<String> ids = new ArrayList<>();
        for (BamuSpReconciliationOrder order:bamuSpReconciliationOrders){
            ids.add(order.getSupplyId());
        }
        if(CollectionUtils.isNotEmpty(ids)){
            queryWrapper.notIn(BamuPoSupply::getId,ids);
        }
        List<BamuPoSupply> contractMaterialList  = iBamupoSupplyService.list(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractMaterialList)){
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private SupplyExcelDto convertToExcelDto(BamuPoSupply bamuSoSupply){
        SupplyExcelDto dto = new SupplyExcelDto();
        BeanUtils.copyProperties(bamuSoSupply,dto);
        dto.setId(bamuSoSupply.getId());
        return dto;
    }
}
